#include<iostream>
#include<string>
#include<websocketpp/server.hpp>
#include<websocketpp/config/asio_no_tls.hpp>
typedef websocketpp::server<websocketpp::config::asio> wsserver;

void Printf(const std::string& str)
{
    std::cout<<str<<std::endl;
}
//有可能需要使用源服务器进行操作，因此传入参数
void HttpHandle(wsserver* src,websocketpp::connection_hdl hdl)
{
    wsserver::connection_ptr conn=src->get_con_from_hdl(hdl);
    std::cout<<"body:"<<conn->get_request_body()<<std::endl;
    websocketpp::http::parser::request req=conn->get_request();
    std::cout<<"method:"<<req.get_method()<<std::endl;
    std::cout<<"uri:"<<req.get_uri()<<std::endl;

    std::string body="<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content_Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);
    wsserver::timer_ptr tm=src->set_timer(5000,std::bind(Printf,"test_timer"));
    tm->cancel();//定时任务的取消，会让定时时间立即被执行
}

void OpenHandle(wsserver* src,websocketpp::connection_hdl hdl)
{
    std::cout<<"websocket握手成功"<<std::endl;
}

void CloseHandle(wsserver* src,websocketpp::connection_hdl hdl)
{
    std::cout<<"websocket连接断开"<<std::endl;
}

void MessageHandle(wsserver* src,websocketpp::connection_hdl hdl,wsserver::message_ptr msg)
{
    std::cout<<"wsmsg:"<<msg->get_payload()<<std::endl;
    std::string rsp="client  say:"+msg->get_payload();
    wsserver::connection_ptr conn=src->get_con_from_hdl(hdl);
    conn->send(rsp,websocketpp::frame::opcode::text);
}

int main()
{
    //创建服务器
    wsserver server;
    //设置日志等级（当前为不打印日志）
    server.set_access_channels(websocketpp::log::alevel::none);
    //初始化asio调度器
    server.init_asio();
    server.set_reuse_addr(true);//设置可重用地址
    //设置回调函数
    server.set_http_handler(std::bind(HttpHandle,&server,std::placeholders::_1));
    server.set_open_handler(std::bind(OpenHandle,&server,std::placeholders::_1));
    server.set_close_handler(std::bind(CloseHandle,&server,std::placeholders::_1));
    server.set_message_handler(std::bind(MessageHandle,&server,std::placeholders::_1,std::placeholders::_2));
    //设置监听端口
    server.listen(8085);
    //开始获取新连接
    server.start_accept();
    //启动服务器
    server.run();//阻塞接口
}